<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Base;
use Closure;
use App\Tables;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(app()->environment() === 'local') { // 本地开发不要验证
            return $next($request);
        }

        if($request->is(['api/login',  'api/checkLogin'])) {
            return $next($request);
        }
        $token = Base::getToken();
        $uid = Base::getUID();
        $find = Tables\Token::where(['uid' => $uid])->first();
        $fail = function() {
            return response()->json(['status' => -1]);
        };
        if(empty($find)){
            return $fail();
        }
        if($token !== $find['token']) {
            return $fail();
        }
        if($find['exp'] < time()) {
            return $fail();
        }
        return $next($request);
    }
}
